package com.zsk.wms.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;

import com.zsk.wms.util.HttpUtil;
import com.zsk.wms.util.SSOClientUtil;

/**
 * SSO 单点登录过滤器
 * 
 * @author keke
 * @date 2020/09/27
 */
public class SSOClientFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        HttpSession session = req.getSession();
        // 1.判断是否有局部的会话，如果有会话直接放行
        Boolean isLogin = (Boolean)session.getAttribute("isLogin");
        if (isLogin != null && isLogin) {
            chain.doFilter(request, response);
            return;
        }
        String path = req.getRequestURI();
        if (path.toLowerCase().contains("login") || path.endsWith(".css") || path.endsWith(".js")
            || path.endsWith(".ico")) {
            // 放行
            chain.doFilter(request, response);
            return;
        }
        // 2.判断地址栏中是否有携带token参数.
        String token = req.getParameter("token");
        if (!StringUtils.isEmpty(token)) {
            // 判断token信息是否由认证中心产生的.
            String httpURL = SSOClientUtil.SERVER_URL_PREFIX + "/verify";
            Map<String, String> params = new HashMap<String, String>();
            params.put("token", token);
            params.put("clientUrl", SSOClientUtil.getClientLogOutUrl());
            params.put("jsessionid", session.getId());
            try {
                String isVerify = HttpUtil.sendHttpRequest(httpURL, params);
                if ("true".equals(isVerify)) {
                    // 如果返回的字符串是true,说明这个token是由统一认证中心产生的.
                    // 创建局部的会话.
                    session.setAttribute("isLogin", true);
                    // 放行该次的请求
                    chain.doFilter(request, response);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 没有局部会话,重定向到统一认证中心,检查是否有其他的系统已经登录过.
        // http://www.sso.com:8443/checkLogin?redirectUrl=http://www.crm.com:8088
        SSOClientUtil.redirectToSSOURL(req, resp);
    }

    @Override
    public void destroy() {

    }
}
